use lazy_static::lazy_static;
use sled::Db;
use std::sync::Mutex;
use tauri::{path, AppHandle, Manager};

pub const FRIENDS_DB_PATH: &str = "data/friends";
pub const MESSAGES_DB_PATH: &str = "data/messages";
// 在运行时初始化数据库
pub fn initialize_databases(app_handle: &AppHandle) {
    *friends_db.lock().unwrap() = init_friends_db(app_handle).into_inner().unwrap();
    *messages_db.lock().unwrap() = init_messages_db(app_handle).into_inner().unwrap();
}
// 使用函数返回 Mutex<Db> 而不是直接在 lazy_static 中初始化
fn init_friends_db(app_handle: &AppHandle) -> Mutex<Db> {
    let appdata_dir = app_handle.path().app_data_dir().unwrap();
    let friends_db_path = appdata_dir.join(FRIENDS_DB_PATH);
    Mutex::new(sled::open(friends_db_path).unwrap())
}

fn init_messages_db(app_handle: &AppHandle) -> Mutex<Db> {
    let appdata_dir = app_handle.path().app_data_dir().unwrap();
    let messages_db_path = appdata_dir.join(MESSAGES_DB_PATH);
    Mutex::new(sled::open(messages_db_path).unwrap())
}
lazy_static! {
    
    // 全局静态变量，用于存储所有打开的数据库
    pub static ref friends_db: Mutex<Db> = Mutex::new(sled::open(FRIENDS_DB_PATH).unwrap());
    pub static ref messages_db: Mutex<Db> = Mutex::new(sled::open(MESSAGES_DB_PATH).unwrap());
}
